import { createApp } from 'vue'

import Cookies from 'js-cookie'
import 'element-plus/dist/index.css'
import locale from 'element-plus/es/locale/lang/zh-cn' // 中文语言
import 'tailwindcss/tailwind.css'
import ElementPlus from 'element-plus'
import '@/assets/styles/element.scss'
import '@/assets/styles/element-2.7.scss'

import VXETablePluginElement from 'vxe-table-plugin-element'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'
import '@/assets/icons/iconfont/index.css'
import '@/assets/styles/index.scss' // global css
import App from './App'
import store from './store'
import router from './router'
// svg图标
import 'virtual:svg-icons-register'
import SvgIcon from '@/components/SvgIcon'
import { defaultTime } from "@/utils/config.js";
// 全局组件
import Public from '@/componentsPublic'
import confirm from '@/plugins/confirm.jsx'
import SelectPersonnel from "@/components/SelectPersonnel";
import DKVui from 'dk-vui'
import 'dk-vui/dist/style.css'


import {
  renderWithQiankun,
  qiankunWindow,
} from 'vite-plugin-qiankun/dist/helper'
import { name as packageName } from '../package.json'

import pinia from '@/store/index'
import keepAliveStore from '@/store/modules/keepalive'
const keepeStore = keepAliveStore(pinia)
import { useRouter } from "vue-router"

import directive from './directive' // directive
import action from '@/utils/action.js'
import { routes } from '@/router/index'
import { initMatomo } from '@/utils/initMatomo'

import CountryFlag from 'vue-country-flag-next'

import api from "@/api/tableForm.js"
let app
function render(props) {
  app = createApp(App)
  initMatomo(app)
  const { container, $parentRouter, routerEvent } = props
  // 主应用全局数据
  app.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange
  app.config.globalProperties.$setGlobalState = props.setGlobalState
  app.config.globalProperties.confirm = confirm
  // 公共配置
  app.config.globalProperties.defaultTime = defaultTime;

  
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
  }
  app.use(router)
  app.use(store)
  app.use(VXETable)
  VXETable.use(VXETablePluginElement)
  app.use(DKVui)
  DKVui.setup({
    keepStore: keepAliveStore,
    useRouter,
    table: {
      scrollHideForm: true,
      formConfig: {
        proxy: {
          mainKey: '_id', // 主键
          query: async({ model_type:scope }) => {
            let res = await api.queryParamsIndex({ scope })
            res.data = res.data.map(v=>({...v,conditions:v.params}))
            return res
          },
          // model_type 类型/ name 保存名称 / sc_id 主键 / conditions保存条件
          save: ({ model_type, name, scope, conditions: params }) => api.queryParamsCreate({ name, scope: model_type, params }),
          remove: async({_id}) => api.queryParamsDelete(`id=${_id}`)
        }
      }
    },
  })

  
  app.use(Public)
  app.component('svg-icon', SvgIcon)
  app.component("select-personnel", SelectPersonnel);
  app.component('CountryFlag', CountryFlag)
  // 使用element-plus 并且设置全局的大小
  app.use(ElementPlus, {
    locale: locale,
    // 支持 large、default、small
    size: Cookies.get('size') || 'default',
  })

  const c = container
    ? container.querySelector('#app')
    : document.getElementById('app')

  if (routerEvent) {
    // 如果首次跳转子页面就直接跳到父级页面
    let path = routes.find(item => item.path === routerEvent.path)
    console.log('path' + path)
    // 页面路由跳转加上?mustJump=true  可以强制跳转子页面  暂未使用 后续自由扩展
    if (
      path &&
      path.mate &&
      path.meta.parentName &&
      !(routerEvent && routerEvent.query && routerEvent.query.mustJump)
    ) {
      let parent = routes.find(item => item.name === path['meta']['parentName'])
      $parentRouter.push(parent.path)
      keepeStore.pushKeepaliveList(parent.name)
      action.setGlobalState({
        changeMicoTabsPath: {
          to: {
            path: parent.path,
            fullPath: parent.path,
            query: {},
          },
          appName: 'oms',
          type: 'change',
        },
      })
      return
    } else {
      const newPath = routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, '/')
      const newFullPath =
        routerEvent.fullPath && routerEvent.fullPath.replace(/\/[^/]*\//, '/')
      router.push(newFullPath)
      let find = routes.find(item => item.path === newPath)
      find && keepeStore.pushKeepaliveList(find.name)
    }

    requestAnimationFrame(() => {
      action.setGlobalState({
        changeMicoTabsPath: {
          type: 'changeLoading',
          loading: false,
        },
      })
    })
  }else{
    // setTimeout(() => {
    //   let query = router?.currentRoute?.value.query
    //   console.log(router?.currentRoute?.value);
    //   // router.push(router.options?.routes?.[0].path)
    //   if(query.type == 'push'){
    //     router.push(`/${query?.path}`)
    //   }
    // }, 100);
  }
  app.mount(c)
  directive(app)
}

renderWithQiankun({
  mount(props) {
    console.log(packageName + ': mount--子应用挂载', props)
    action.setActions(props)
    render(props)
  },
  bootstrap() {
    console.log(packageName + ': bootstrap')
  },
  // unmount(props) {
  //   keepeStore.clearKeepaliveList()
  //   app.unmount();
  //   app._container.innerHTML = ''
  //   app = null
  //   console.error(packageName + ': unmount--销毁子应用')
  // },
  async unmount(props) {
    await keepeStore.clearKeepaliveList()
    app.unmount()
    app._container.innerHTML = ""
    app = null
    console.error(packageName + ": unmount--销毁子应用")
  },

  update(props) {
    let { routerEvent } = props
    // if (routerEvent) {
    //   switch (routerEvent.type) {
    //     case 'push':
    //       {
    //         console.log('执行添加')
    //         const newPath =
    //           routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, '/')
    //         const newFullPath =
    //           routerEvent.fullPath &&
    //           routerEvent.fullPath.replace(/\/[^/]*\//, '/')
    //         router.push(newFullPath)
    //         console.log(newPath);
    //         console.log(routes);
    //         const path = routes.find(item => item.path === newPath)
    //         console.log(777);
    //         console.log(path);
    //         keepeStore.pushKeepaliveList(path?.name)
    //       }
    //       break
    //     case 'replace':
    //       {
    //         console.log('执行替换')
    //         const newPath =
    //           routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, '/')
    //         const newFullPath =
    //           routerEvent.fullPath &&
    //           routerEvent.fullPath.replace(/\/[^/]*\//, '/')
    //         router.replace(newFullPath)
    //       }
    //       break
    //     case 'close':
    //       {
    //         console.log('执行关闭')
    //         const newPath =
    //           routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, '/')
    //         keepeStore.closeKeepaliveList(
    //           routes.find(item => item.path === newPath)
    //         )
    //       }
    //       break
    //     case 'visible':
    //       {
    //         console.warn('visible')
    //       }
    //       break
    //   }
    // }
    if (routerEvent) {
      const newPath = routerEvent.path?.replace(/\/[^/]*\//, '/');
      if (!newPath) return
      const hasId = ['/edit/', '/view/', '/create/'].find(d => newPath.indexOf(d) > -1)
      let id = ''
      if (hasId) {
        id = newPath.slice(newPath.lastIndexOf('/') + 1)
      }
      switch (routerEvent.type) {
        case 'push': {
          router.push({...routerEvent, path: newPath})
          const path = routes.find(item => item.path.replace(':id', id) === newPath)
          path && keepeStore.pushKeepaliveList(path.name)
        }
          break
        case 'replace': {
          router.replace({...routerEvent, path: newPath})
        }
          break
        case 'close': {
          console.log('关闭缓存', newPath)
          const path = routes.find(item => item.path.replace(':id', id) === newPath)
          path && keepeStore.closeKeepaliveList(path)
        }
          break
        case 'visible': {
          console.warn('visible')
        }
          break
      }
    }
  },
})

if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render({})
}
